﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Thesis_v01
{
   public partial class ViewEnquiries : Form
   {
      private const int waitTime = 5000;
      private int classID;
      private bool isRunning;

      private struct UpdateItem
      {
         public bool refreshList;
         public string enquiry;
      }

      public ViewEnquiries(int lessonID)
      {
         InitializeComponent();
         classID = lessonID;
      }

      private void ViewEnquiries_Load(object sender, EventArgs e)
      {
         isRunning = true;
         enquiryListView.Items.Clear();
         backgroundWorker.RunWorkerAsync();
      }

      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
         DBConnection dbConn = new DBConnection();
         dbConn.OnlyOpenConnection();

         while (isRunning)
         {
            if (backgroundWorker.CancellationPending)
            {
               e.Cancel = true;
               break;
            }
            ArrayList enquiries = dbConn.RetrieveEnquiries(classID);

            bool clearList = true;
            foreach (string enquiry in enquiries)
            {
               UpdateItem updateProgress = new UpdateItem();
               updateProgress.refreshList = clearList;
               updateProgress.enquiry = enquiry;
               backgroundWorker.ReportProgress(0, updateProgress);
               clearList = false;
            }

            Thread.Sleep(waitTime);
         }

         dbConn.OnlyCloseConnection();
      }

      private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
         UpdateItem update = (UpdateItem)e.UserState;
         if (update.refreshList)
         {
            enquiryListView.Items.Clear();
         }
         enquiryListView.Items.Add(update.enquiry);
      }

      private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
         //isRunning = false;
         this.Cursor = Cursors.Default;
      }

      private void ViewEnquiries_FormClosing(object sender, FormClosingEventArgs e)
      {
         isRunning = false;
         if (backgroundWorker.IsBusy)
         {
            backgroundWorker.CancelAsync();
            this.Cursor = Cursors.WaitCursor;
            this.Text = "Closing...";
         }

         MainApp main = (MainApp)this.MdiParent;
         main.ToggleEnquiryButtonEnable();
         //main.ToggleEditCourseButtonEnable();
      }
   }
}
